package org.example.school.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.school.entity.Parents;
import org.example.school.entity.StudentParentRelations;
import org.example.school.entity.Students;
import org.example.school.entity.Users;
import org.example.school.mapper.ParentsMapper;
import org.example.school.mapper.StudentParentRelationsMapper;
import org.example.school.mapper.StudentsMapper;
import org.example.school.mapper.UsersMapper;
import org.example.school.model.dto.StudentProfileDTO;
import org.example.school.model.dto.UpdateStudentProfileDTO;
import org.example.school.service.IStudentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生基本信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-09-28
 */
@Service
public class StudentsServiceImpl extends ServiceImpl<StudentsMapper, Students> implements IStudentsService {

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private StudentParentRelationsMapper studentParentRelationsMapper;

    @Autowired
    private ParentsMapper parentsMapper;


    @Override
    public StudentProfileDTO getStudentProfile(Long userId) {
        // 1. 使用自定义SQL查询学生、班级、用户基本信息
        StudentProfileDTO profileDTO = studentsMapper.getStudentProfileByUserId(userId);
        if (profileDTO == null) {
            return null; // 或者抛出异常
        }

        // 2. 单独查询学生信息以获取学生ID
        Students student = this.getOne(new LambdaQueryWrapper<Students>().eq(Students::getUserId, userId));
        if (student == null) {
            return null;
        }

        // 3. 根据学生ID查询所有家长关系
        List<StudentParentRelations> relations = studentParentRelationsMapper.selectList(
                new LambdaQueryWrapper<StudentParentRelations>().eq(StudentParentRelations::getStudentId, student.getId())
        );
        if (!relations.isEmpty()) {
            // 4. 获取所有家长ID
            List<Long> parentIds = relations.stream().map(StudentParentRelations::getParentId).collect(Collectors.toList());

            // 5. 查询所有家长信息
            List<Parents> parents = parentsMapper.selectBatchIds(parentIds);

            // 6. 组装家长信息到DTO
            List<StudentProfileDTO.ParentInfo> parentInfos = relations.stream().map(relation -> {
                StudentProfileDTO.ParentInfo info = new StudentProfileDTO.ParentInfo();
                info.setRelationship(relation.getRelationship());
                // 找到对应的家长姓名
                parents.stream()
                        .filter(p -> p.getId().equals(relation.getParentId()))
                        .findFirst()
                        .ifPresent(p -> {
                            info.setFullName(p.getFullName());
                            info.setPhoneNumber(p.getPhoneNumber());
                        });
                return info;
            }).collect(Collectors.toList());

            profileDTO.setParentInfos(parentInfos);
        }

        return profileDTO;
    }

    @Override
    @Transactional
    public boolean updateStudentProfile(UpdateStudentProfileDTO dto, Long userId) {
        // 学生只能修改user表中的信息，例如电话号码
        Users user = usersMapper.selectById(userId);
        if (user == null) {
            return false;
        }

        user.setPhoneNumber(dto.getPhoneNumber());
        return usersMapper.updateById(user) > 0;
    }
}